<?php
/**
 * Created by PhpStorm.
 * User: koterwong
 * Date: 2017/8/29
 * Time: 16:55
 */

namespace app\api\controller;

use app\api\model\UserModel;
use think\Db;
use think\Validate;
use cmf\lib\Upload;

class UserController extends ApiBaseController
{

    public function getAvatar()
    {
        $mobile = input('mobile');
        $avatar = Db::name('user')->where('user_login', $mobile)->value('avatar');
        $avatar=cmf_get_image_preview_url($avatar);
        if (!empty($avatar)) {
            returnData(API_SUCCESS, '获取成功', ['avatar' => $avatar,]);
        } else {
            returnCommonError('获取失败');
        }
    }

    //修改头像
    public function editAvatar()
    {
        $mobile = input('mobile');
        $uploader = new Upload();

        $result = $uploader->upload();

        if ($result === false) {
            //$this->error($uploader->getError());
             returnData(-1,'上传失败',$uploader->getError());
        } else {

            $url= $result['filepath'];
            $avatar=cmf_get_image_preview_url($url);
            if($url) {
                $avatar = Db::name('user')->where('user_login', $mobile)->setField('avatar',$url);
                $data['avatar']=$avatar;
                returnData(API_SUCCESS, '修改成功', $data);
            }
            //$this->success("上传成功!", '', $result);
        }

    }


    //修改昵称
    public function editNick()
    {
        $validate = new Validate([
            'token' => 'require',
            'nickname' => 'require|min:2|max:32',
        ]);

        $validate->message([
            'token.require' => 'token不能为空',
            'nickname.require' => '昵称不能为空',
            'nickname.min' => '昵称不能小于两个字符',
            'nickname.max' => '昵称不能超过32个字符',
        ]);

        if (!$validate->check($this->request->post())) {
            returnError(API_PARAM_ERROR, $validate->getError());
        };

        $userModel = new UserModel();
        $result = $userModel->editNick([
            'user_id' => API_UID,
            'user_nickname' => input('nickname'),
        ]);

        if ($result == 1) {
            returnData(API_SUCCESS, '编辑成功');
        } else {
            returnCommonError('编辑失败');
        }
    }
}